/**
 * @file 工单操作-取消
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'list_modify_common', '$http','oms_work_config'], function (exports) {
    var $ = layui.$,
        form = layui.form;
    var opCommonUtils = layui.list_modify_common;
    var layer = layui.layer;
    var $http = layui.$http;
    var config = layui.oms_work_config;

    var tip = tips || "";

    /**
     * 初始化页面
     */
    function initPage() {
        initDuplicateOrderId();
        Number.prototype.div = function (arg) {
            var t1 = 0, t2 = 0, r1, r2;
            try {
                t1 = this.toString().split(".")[1].length
            } catch (e) {
            }
            try {
                t2 = arg.toString().split(".")[1].length
            } catch (e) {
            }
            with (Math) {
                r1 = Number(this.toString().replace(".", ""));
                r2 = Number(arg.toString().replace(".", ""));
                return (r1 / r2) * pow(10, t2 - t1);
            }
        };
        if (prepayAmount == null && channelPrepayAmount == null) {
            $('#refundAmountItem').val('').hide();
            return;
        }
        var refundAmount = (prepayAmount + channelPrepayAmount).div(100);
        $('#refundAmount').html(refundAmount);
    }

    form.verify({
        reason: function (reason) {
            var _msg = '';

            var ajaxxoption = {
                type: "post",
                async: false,
                url: "/work/modify/ajax/verifyCancelOrderDuplicate.action",
                cache: false,
                data: {
                    orderId: orderId,
                    workId: workId,
                    duplicateCode: reason,
                },
                success: function (data) {
                    if (!data.statusBool) {
                        _msg = data.message;
                    }
                }
            };
            $.ajax(ajaxxoption);

            return _msg;
        }
    });
    
    function initDuplicateOrderId() {
        let $input = $('#reason input[type=radio]:checked');
        if ($input != null && $input.length > 0) {
            if (duplicateMapId == $input.val().split("-")[0]) {
                var $wrapper = $('#originalCode-wrapper');
                var innerHTML = $('#originalCodeTemplate').html();
                $wrapper.html(innerHTML).show();
                form.render();
                var text = $input.attr('data-ext');
                if (text == undefined) {
                    text = "";
                }
                $("#remark").html(text);
            }
        }
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {

        $(document).ready(function () {
            var tips;
            $(".layui-form-radio").mouseover(function () {
                let content = $(this).prev().attr("data-ext");
                if (content) {
                    tips = layer.tips(content, this, {time:0, tips:[2, '#009688']});
                }
            });
            $(".layui-form-radio").mouseout(function () {
                if (tips) {
                    layer.close(tips);
                }
            });
        });

        $('#review-success').show();

        form.on('radio(reviewStatus)', function (data) {
            if (+data.value === 2) {
                $('#review-success').show();
            } else {
                $('#review-success').hide();
            }
        });


        $(':reset').on('click', function () {
            $('form')[0].reset();
            $('#originalCode').remove();
        });

        /*form.on('radio(reason)', function (data) {
            var $this = $(this);
            var text = $this.attr('data-ext');
            if (text == undefined) {
                text = "";
            }
            $("#remark").html(text);
        })*/

        /*form.on('checkbox(reason)', function (data) {
            if (duplicateMapId === data.value) {
                var $wrapper = $('#originalCode-wrapper');
                if (data.elem.checked) {
                    var innerHTML = $('#originalCodeTemplate').html();
                    $wrapper.html(innerHTML).show();
                    form.render();
                } else {
                    $wrapper.html('').hide();
                }
            }
        });*/

        function getMapName(mapId) {
            for (var i = 0; i < cancelList.length; i++) {
                var cancelListElement = cancelList[i];
                if (cancelListElement.value.toString() === mapId) {
                    return cancelListElement.text;
                }
            }
        }

        form.on('submit(save)', function (data) {
            // 启用重复框
            $("input[type=radio]:disabled").removeAttr("disabled");

            var detailDTOList = [];
            var originalCode = '';
            var content = '';
            var reviewStatus = '';

            var formData = $(data.form).serializeArray();
            for (var i = 0; i < formData.length; i++) {
                var formDatum = formData[i];
                if (formDatum.name === 'reason') {
                    var map = formDatum.value.split("-");
                    var OrderRemarkDetailDTO = {
                        mapId: map[0],
                        mapName: map[1]
                    };
                    detailDTOList.push(OrderRemarkDetailDTO);
                }
                if (formDatum.name === 'originalCode') {
                    originalCode = formDatum.value;
                }
                if (formDatum.name === 'content') {
                    content = formDatum.value;
                }
                if (formDatum.name === 'reviewStatus') {
                    reviewStatus = formDatum.value;
                }
            }

            // 退款审核！=不通过，校验
            if (detailDTOList.length == 0 && reviewStatus != '3') {
                layer.msg("请选择取消缘由！");
                $("input[data-type='2']").attr("disabled", "disabled");
                form.render();
                return false;
            }

            var returnData = {
                originalCode: originalCode,
                content: content,
                detailDTOList: detailDTOList,
                orderId: orderId,
                workId: workId,
                reviewStatus: reviewStatus,
                casSign: $('#casSign').val()
            };

            if (tip.length == 0) {
                submit(returnData, data);
            } else {
                layer.confirm(tip, {
                    btn: ['确认取消','取消'] //按钮
                }, function(){
                    submit(returnData, data);
                }, function(){
                    $("input[data-type='2']").attr("disabled", "disabled");
                    form.render();
                });
            }
        });

        form.on('submit(cancelAndSave)', function (data) {
            // 启用重复框
            $("input[type=radio]:disabled").removeAttr("disabled");

            var detailDTOList = [];
            var originalCode = '';
            var content = '';
            var reviewStatus = '';

            var formData = $(data.form).serializeArray();
            for (var i = 0; i < formData.length; i++) {
                var formDatum = formData[i];
                if (formDatum.name === 'reason') {
                    var map = formDatum.value.split("-");
                    var OrderRemarkDetailDTO = {
                        mapId: map[0],
                        mapName: map[1]
                    };
                    detailDTOList.push(OrderRemarkDetailDTO);
                }
                if (formDatum.name === 'originalCode') {
                    originalCode = formDatum.value;
                }
                if (formDatum.name === 'content') {
                    content = formDatum.value;
                }
                if (formDatum.name === 'reviewStatus') {
                    reviewStatus = formDatum.value;
                }
            }

            // 退款审核！=不通过，校验
            if (detailDTOList.length == 0 && reviewStatus != '3') {
                layer.msg("请选择取消缘由！");
                $("input[data-type='2']").attr("disabled", "disabled");
                form.render();
                return false;
            }

            var returnData = {
                originalCode: originalCode,
                content: content,
                detailDTOList: detailDTOList,
                orderId: orderId,
                workId: workId,
                reviewStatus: reviewStatus,
                casSign: $('#casSign').val(),
                createNewOrder: 2
            };

            if (tip.length == 0) {
                submit(returnData, data);
            } else {
                layer.confirm(tip, {
                    btn: ['确认取消','取消'] //按钮
                }, function(){
                    submit(returnData, data);
                }, function(){
                    $("input[data-type='2']").attr("disabled", "disabled");
                    form.render();
                });
            }
        });

        // 跳转跟单列表
        function jumpCancelList() {
            parent.layer.closeAll();
            if (top.isCallCenter) {
                top.layui.index.openTabsPage(config.trackHost + "/apply/cancel/list.action?orderId=" + orderId, '工单操作：取消列表');
                return;
            }
            parent.layui.index.openTabsPage(config.trackHost + "/apply/cancel/list.action?orderId=" + orderId, '取消列表');
        }

        function openCancelConfirm(returnData, data, content, status) {
            var btn;
            if (status == 88140005) {
                btn = ['等工程师处理', '直接取消'];
            }else if (status == 88140006) {
                btn = ['前去处理', '直接取消'];
            }
            layer.open({
                type: 1,
                title: "提示",
                btn: btn,
                area: 'auto',
                shade: [0.8, '#393D49'],
                scrollbar: false,
                content: '<div style="text-align:center; line-height: 100px">' + content + '</div>',
                yes: function (index, layero) {
                    layer.close(index); //关闭弹层
                    if (status == 88140006) {
                        layer.closeAll();
                        jumpCancelList();
                    }
                }
                , btn2: function (index, layero) {
                    layer.close(index); //关闭弹层
                    // 不校验取消申请
                    returnData.entranceId = 92;
                    submit(returnData, data);
                }
            });
        }

        function submit(returnData, data) {
            var loading = layer.open({type: 3});

            var url = '/work/modify/save/cancel.action';

            $.ajax({
                url: url,
                type: "POST",
                async: false, //改为同步请求
                data: JSON.stringify(returnData),
                contentType: 'application/json;charset=utf-8',
                success: function (res) {
                    layer.close(loading);
                    switch (res.status) {
                        case 200: {
                            layer.msg('操作成功', {icon: 1, time: 1000}, function () {
                                opCommonUtils.goOperateHome();
                            });
                            break;
                        }
                        case 88140005:{
                            openCancelConfirm(returnData, data, res.message, res.status);
                            break;
                        }
                        case 88140006:{
                            openCancelConfirm(returnData, data, res.message, res.status);
                            break;
                        }
                        default:
                            layer.msg(res.message);
                            $("input[data-type='2']").attr("disabled", "disabled");
                            form.render();
                            break;
                    }
                }
            });
            return false;
        }


    }

    // 程序入口
    function init() {

        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();

    }


// 初始化
    init();

    exports('oms_work_modify_cancel');
});
